package com.broad.data.storage.mybatis.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "com.broad.data.storage.mybatis",sqlSessionFactoryRef = "myBatisSqlSession")
public class MyBatisDatasourceConfiguration {

        @Value("${spring.datasource.driver-class-name:com.mysql.jdbc.Driver}")
        private String driverClassName;

        @Value("${spring.datasource.password:123456}")
        private String password;

        @Value("${spring.datasource.username:root}")
        private String username;


        @Value("${spring.datasource.url:jdbc:mysql://localhost:3306/hos}")
        private String jdbcUrl;

        @Primary
        @Bean(name = "mybatisDatasource")
        public DataSource dataSource() {
            HikariConfig config = new HikariConfig();
            config.setPassword(password);
            config.setUsername(username);
            config.setJdbcUrl(jdbcUrl);
            config.setDriverClassName(driverClassName);
            return new HikariDataSource(config);
        }


        @Bean(name = "myBatisSqlSession")
        public SqlSessionFactory sqlSessionFactory(@Qualifier(value = "mybatisDatasource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
            factoryBean.setDataSource(dataSource);
            factoryBean.setSqlSessionFactoryBuilder(new SqlSessionFactoryBuilder());
            return factoryBean.getObject();
        }

        @Bean(name = "primaryTransactionManager")
        @Primary
        public DataSourceTransactionManager transactionManager() {
            return new DataSourceTransactionManager(this.dataSource());
        }


}
